package library.and.xps.com.step.view.activity;

import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jude.utils.JUtils;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnClickListener;
import com.orhanobut.logger.Logger;
import com.squareup.okhttp.Request;
import com.zhy.autolayout.AutoRelativeLayout;

import java.util.List;

import library.and.xps.com.step.App;
import library.and.xps.com.step.R;
import library.and.xps.com.step.URLConstants;
import library.and.xps.com.step.adapter.ChangeTeamListAdapter;
import library.and.xps.com.step.m.model.ChangeTeam;
import library.and.xps.com.step.m.model.JoinedTeam;
import library.and.xps.com.step.m.model.Team;
import library.and.xps.com.step.m.model.TeamsJoined;
import library.and.xps.com.step.m.netapi.OkHttpClientUtils;
import library.and.xps.com.step.net.ResponceWrapper;
import library.and.xps.com.step.util.CommonUtils;
import library.and.xps.com.step.util.HttpResponsHelper;
import library.and.xps.com.step.util.RequestCallback;
import library.and.xps.com.step.view.base.BaseActivity;

public class SwitchTeamActivity extends BaseActivity implements OnClickListener {
    private ImageView actionbar_iv_back;
    private TextView actionbar_tv_title;
    private TextView actionbar_tv_right;
    private AutoRelativeLayout actionbar_al;
    private TextView tv_current_team;
    private ImageView iv_team_detail_avatar;
    private TextView tv_team_detail_teamName;
    private TextView tv_tv_team_detail_teamId;
    private TextView tv_tv_team_detail_org_address;
    private TextView tv_current_;
    private ListView list_teams;
    private TextView tv_current_tname;
    private TextView tv_current_tId;
    private TextView tv_createnickname;
    ChangeTeamListAdapter changeTeamListAdapter;
    List<TeamsJoined.ListBean> list;
    private String REQUEST_CHANGETEAM = "REQUEST_CHANGETEAM";
    int selectedTeamId;

    @Override
    protected int getLayout() {
        return R.layout.change_team_activity;
    }

    @Override
    protected void setData() {
        changeTeamListAdapter = new ChangeTeamListAdapter(this);
        list_teams.setAdapter(changeTeamListAdapter);
        list_teams.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TeamsJoined.ListBean selectedItem = ((ChangeTeamListAdapter) parent.getAdapter()).getData().get(position);
                selectedTeamId = selectedItem.getTeamid();
                showHintDialog("确定切换团队吗?", SwitchTeamActivity.this);
            }
        });
        getTeamData();

    }

    void getTeamData() {
        String data = URLConstants.TEAM.TeamJoined + "?" + "userid=" + getUser().getUserid();
        OkHttpClientUtils.getDataAsync(this, data, new RequestCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                e.printStackTrace();
                dissmisDialog();
            }

            @Override
            public void onResponse(ResponceWrapper response) {
                dissmisDialog();
                Logger.json(response.getBody());
                TeamsJoined teams = new Gson().fromJson(response.getBody(), TeamsJoined.class);
                if (HttpResponsHelper.SuccessResponce(teams)) {
                    list = teams.getList();
                    setAdapterData(list);
                    setCurrentTeaminfo(teams);
                }
            }

            @Override
            public void onStart() {
                showDialog();
            }
        }, "");
    }

    void setAdapterData(List<TeamsJoined.ListBean> list) {
        changeTeamListAdapter.addData(list);
        CommonUtils.resetListViewHeight(list_teams);
    }

    void setCurrentTeaminfo(TeamsJoined teams) {
        tv_current_tname.setText("团队名:" + teams.getObj().getTname() + "");
        tv_createnickname.setText("创建人:" + teams.getObj().getCreatenickname() + "");
        CommonUtils.setUpimg(this, iv_team_detail_avatar, teams.getObj().getMark(), true);
    }

    @Override
    protected void init() {
        if (getUser() == null) return;
        initView();
    }

    private void initView() {
        actionbar_iv_back = (ImageView) findViewById(R.id.actionbar_iv_back);
        actionbar_tv_title = (TextView) findViewById(R.id.actionbar_tv_title);
        actionbar_tv_right = (TextView) findViewById(R.id.actionbar_tv_right);
        actionbar_al = (AutoRelativeLayout) findViewById(R.id.actionbar_al);
        tv_current_tname = (TextView) findViewById(R.id.tv_current_tname);
        tv_current_tId = (TextView) findViewById(R.id.tv_current_tId);
        tv_createnickname = (TextView) findViewById(R.id.tv_createnickname);
        tv_current_team = (TextView) findViewById(R.id.tv_current_team);
        iv_team_detail_avatar = (ImageView) findViewById(R.id.iv_team_detail_avatar);
        tv_team_detail_teamName = (TextView) findViewById(R.id.tv_team_detail_teamName);
        tv_tv_team_detail_teamId = (TextView) findViewById(R.id.tv_tv_team_detail_teamId);
        tv_tv_team_detail_org_address = (TextView) findViewById(R.id.tv_tv_team_detail_org_address);
        tv_current_ = (TextView) findViewById(R.id.tv_current_);
        list_teams = (ListView) findViewById(R.id.list_teams);

        actionbar_tv_title.setText("改变团队");
        actionbar_iv_back.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.actionbar_iv_back:
                finish();
                break;
        }
    }

    @Override
    public void onClick(DialogPlus dialog, View view) {
        switch (view.getId()) {
            case R.id.footer_close_button:
                dialog.dismiss();
                break;
            case R.id.footer_confirm_button:
                switchTeamTo();
                dialog.dismiss();
                break;
        }

    }

    //切换团队
    void switchTeamTo() {
        String data = URLConstants.TEAM.ChangeTeam + "?userid=" + getUser().getUserid() + "&teamid=" + selectedTeamId;
        OkHttpClientUtils.getDataAsync(this, data, new RequestCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                e.printStackTrace();
                dissmisDialog();
            }

            @Override
            public void onResponse(ResponceWrapper response) {
                dissmisDialog();
                ChangeTeam changeTeam = new Gson().fromJson(response.getBody(), ChangeTeam.class);

                if (HttpResponsHelper.SuccessResponce(changeTeam)) {
                    getCurrentTeam();

                } else {
                    JUtils.Toast("切换团队失败!");
                }

            }

            @Override
            public void onStart() {
                showDialog();
            }
        }, REQUEST_CHANGETEAM);

    }

    //查询保存当前团队信息
    void getCurrentTeam() {
        if (getUser() == null || !JUtils.isNetWorkAvilable()) return;

        String data = URLConstants.TEAM.GetMyTeam + "?" + "userid=" + getUser().getUserid();
        OkHttpClientUtils.getDataAsync(App.getInstance().getApplicationContext(), data, new RequestCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                if (e instanceof RuntimeException) {
                    JUtils.Toast(e.getMessage());
                }
                dissmisDialog();
            }

            @Override
            public void onResponse(ResponceWrapper response) {
                dissmisDialog();
                if (!HttpResponsHelper.SuccessResponce(response)) {
                    finish();
                    return;
                }
                String json = response.getBody();
                JoinedTeam joinTeamRes = new Gson().fromJson(json, JoinedTeam.class);

                if (HttpResponsHelper.SuccessResponce(joinTeamRes)) {

                    realm.beginTransaction();
                    Team team = new Team();
                    team.setAddress(joinTeamRes.getObj().getAddress());
                    team.setCreatenickname(joinTeamRes.getObj().getCreatenickname());
                    team.setCreater(joinTeamRes.getObj().getCreater() + "");
                    team.setCreatetime(joinTeamRes.getObj().getCreatetime() + "");
                    team.setTname(joinTeamRes.getObj().getTname());
                    team.setEnterprise(joinTeamRes.getObj().getEnterprise());
                    team.setEnterpriseid(joinTeamRes.getObj().getEnterpriseid() + "");
                    team.setDescription(joinTeamRes.getObj().getDescription());
                    team.setType(joinTeamRes.getObj().getType() + "");
                    team.setMarker(joinTeamRes.getObj().getMark());
                    team.setEmail(joinTeamRes.getObj().getEmail());
                    team.setTeamId(joinTeamRes.getObj().getTeamid() + "");
                    team.setIntname(joinTeamRes.getObj().getIntname());
                    team.setRole(joinTeamRes.getObj().getRole());
                    if (joinTeamRes.getObj().getIsno() == -1) {
                        team.setPassWordEnable(false);
                    } else if (joinTeamRes.getObj().getIsno() == 0) {
                        team.setPassWordEnable(true);
                    }
                    getUser().getTeams().clear();
                    getUser().getTeams().add(team);
                    realm.commitTransaction();
                    finish();
                }else {
                    JUtils.Toast("错误!");
                }
            }

            @Override
            public void onStart() {
                showDialogNoCancel();
            }
        }, "");

    }

}
